package designpattern.command.llm.command;

import java.util.ArrayDeque;
import java.util.Deque;
import designpattern.command.llm.model.StringBuf;
import java.util.function.Consumer;

public class CommandExec {
    private final StringBuf stringBuf = new StringBuf();
    private final Deque<Command> undoStack = new ArrayDeque<>();
    private final Deque<Command> redoStack = new ArrayDeque<>();

    // 新增错误处理器接口
    private Consumer<String> errorHandler;
    
    // 设置错误处理器
    public void setErrorHandler(Consumer<String> errorHandler) {
        this.errorHandler = errorHandler;
    }
    
    // 处理错误消息
    private void handleError(String message) {
        if (errorHandler != null) {
            errorHandler.accept(message);
        }
    }

    public boolean executeCommand(Command command) {
        try {
            command.execute();
            undoStack.push(command);
            redoStack.clear();
            return true;
        } catch (IllegalArgumentException e) {
            handleError(e.getMessage());  // 替换为错误处理器调用
            return false;
        }
    }

    public boolean undo() {
        if (!undoStack.isEmpty()) {
            Command command = undoStack.pop();
            try {
                command.undo();
                redoStack.push(command);
                return true;
            } catch (IllegalArgumentException e) {
                handleError("撤销失败: " + e.getMessage());
                return false;
            }
        } else {
            handleError("没有可撤销的操作");  // 替换为错误处理器调用
            return false;
        }
    }

    public boolean redo() {
        if (!redoStack.isEmpty()) {
            Command command = redoStack.pop();
            try {
                command.execute();
                undoStack.push(command);
                return true;
            } catch (IllegalArgumentException e) {
                handleError("重做失败: " + e.getMessage());
                return false;
            }
        } else {
            handleError("没有可重做的操作");  // 替换为错误处理器调用
            return false;
        }
    }

    public String getContent() {
        return stringBuf.getContent();
    }

    // 标记为废弃，保留向后兼容性
    @Deprecated
    public void displayContent() {
        System.out.println("当前内容: [" + getContent() + "]");
    }

    public void append(String text) {
        executeCommand(new AppendCommand(stringBuf, text));
    }
    
    public void insert(int position, String text) {
        executeCommand(new InsertCommand(stringBuf, position, text));
    }
    
    public void delete(int position, int length) {
        executeCommand(new DeleteCommand(stringBuf, position, length));
    }
    
    public StringBuf getStringBuf() {
        return stringBuf;
    }
}